package route

import (
	"encoding/json"
	"web/pool"
	"web/process"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

//plain 模式处理
func PlaHandle(app *iris.Application) {

	//plain /v1路由
	v1 := app.Party("/v1")
	{
		app.Logger().Info(v1)
	}

	//输出html
	// 请求方式: GET
	// 访问地址: http://localhost:2222/welcome
	app.Handle("GET", "/welcome", func(ctx iris.Context) {
		ctx.HTML("<h1>Welcome</h1>")
	})
	//输出字符串
	// 类似于 app.Handle("GET", "/ping", [...])
	// 请求方式: GET
	// 请求地址: http://localhost:8080/ping
	app.Get("/ping", func(ctx iris.Context) {
		ctx.WriteString("pong")
	})
	//输出json
	// 请求方式: GET
	// 请求地址: http://localhost:8080/hello
	app.Get("/hello/{name:string}", func(ctx iris.Context) {
		//idString := ctx.URLParam("id")
		name := ctx.Params().GetString("name")
		ctx.JSON(name)
	})

	//2.处理post请求
	//正常的表单提交的形式    body当中 类型为x-www-form-urlencoded
	app.Post("postLogin", func(context iris.Context) {
		path := context.Path()
		app.Logger().Info(path)
		username := context.PostValue("username") //接收post参数 username
		pass := context.PostValue("pass")         //接收post参数 pass
		app.Logger().Info(username, "    ", pass)
		context.HTML(username + "----" + pass)
	})

	//2.1 处理post请求
	//前端传递的是json字符串过来 body当中类型为：raw 内容为json字符串：{"username":"hushaoliang","pass":111111111}
	app.Post("/postJson", func(context iris.Context) {
		path := context.Path()
		app.Logger().Info("请求的路径是:" + path)
		//json数据解析
		var user User //需要用一个结构体来存放数据 并且结构体当中要有tag标签
		//context.ReadJson() 里面传入的是结构体的指针类型 内存地址
		if err := context.ReadJSON(&user); err != nil {
			panic(err.Error())
		}
		context.Writef("Received:%#+v\n", user)
	})
}

//第一种智能处理请求
//url：http://localhost:8009
//type：Get
func (uc *UserController) Get() string { //给控制器声明一个Get方法
	iris.New().Logger().Info(" Get 请求 ")
	return "hell world"
}
func (uc *UserController) Post() { //给控制器声明一个Post方法

	username := uc.Ctx.PostValue("username") //接收post参数 username
	pass := uc.Ctx.PostValue("pass")         //接收post参数 pass
	//	app.Logger().Info(username, "    ", pass)
	uc.Ctx.HTML(username + "----" + pass)

	iris.New().Logger().Info(" post 请求 ")
	iris.New().Logger().Info(username, "   ", pass)
}
func (uc *UserController) Put() mvc.Result { //给控制器声明一个Put方法
	iris.New().Logger().Info(" put 请求 ")
	return mvc.Response{
		ContentType: "text/html",
		Text:        "<h1>Welcome</h1>",
	}
}

//第二种智能处理请求
//url：http://localhost:8009/info
//type：Get
func (uc *UserController) GetInfo() mvc.Result { //Info和路径一致，首字母大写
	iris.New().Logger().Info(" get 请求, 请求路径为info ")
	return mvc.Response{
		//返回到前端就是json格式
		Object: map[string]interface{}{
			"code":     1,
			"msessage": "请求成功",
		},
	}
}

func (c *UserController) GetPing() string {
	return "ping"
}

func (c *UserController) GetHello() interface{} {
	return map[string]string{
		"message": "Hello World",
	}
}

//第三种智能处理请求
//BeforeActivation自动执行的方法
func (uc *UserController) BeforeActivation(a mvc.BeforeActivation) {
	a.Handle("GET", "/nwdaf/list", "Nwdaf_list") //指定哪一个方法来处理这个请求
	a.Handle("GET", "/nwdaf/NSI_LOAD_LEVEL", "Nwdaf_nsilevel")
	a.Handle("GET", "/nwdaf/{subscrptionId:string}", "Nwdaf_subres")
}

func (uc *UserController) Nwdaf_list() {

	uc.notify = make(chan bool, 1)
	defer close(uc.notify)
	uc.protype = sublist
	pool.Ppool.JobQueue <- uc
	for {
		select {
		case <-uc.notify:
			return
		}
	}
	//time.Sleep(time.Duration(2) * time.Second)
}

func (uc *UserController) Nwdaf_nsilevel() {

	uc.notify = make(chan bool, 1)
	defer close(uc.notify)
	uc.protype = nsilevel
	pool.Ppool.JobQueue <- uc
	for {
		select {
		case <-uc.notify:
			return
		}
	}
	//time.Sleep(time.Duration(2) * time.Second)
}

func (uc *UserController) Nwdaf_subres(subscrptionId string) {

	uc.notify = make(chan bool, 1)
	defer close(uc.notify)
	uc.protype = subres
	uc.param = make(map[string]string)
	uc.param["subscrptionId"] = subscrptionId
	pool.Ppool.JobQueue <- uc
	for {
		select {
		case <-uc.notify:
			return
		}
	}
}

func (uc *UserController) list() string {

	iris.New().Logger().Info(" Nwdaf_list ")
	//return ""
	startDateTime := uc.Ctx.URLParam("startDateTime")
	startDateTime += "T00:00:00.000Z"
	endDateTime := uc.Ctx.URLParam("endDateTime")
	endDateTime += "T24:00:00.000Z"

	uc.Ctx.ContentType("application/json")
	return process.Find_sublist(startDateTime, endDateTime)
}

func (uc *UserController) nsilevel() string {

	iris.New().Logger().Info(" Nwdaf_nsilevel ")
	//return ""
	startDateTime := uc.Ctx.URLParam("startDateTime")
	startDateTime += "T00:00:00.000Z"
	endDateTime := uc.Ctx.URLParam("endDateTime")
	endDateTime += "T24:00:00.000Z"

	uc.Ctx.ContentType("application/json")
	return process.Find_level(startDateTime, endDateTime)
}

func (uc *UserController) subres(subscrptionId string) string {

	iris.New().Logger().Info(" Nwdaf_subres ")
	//return ""
	uc.Ctx.ContentType("application/json")
	resp := process.Find_subinfo(subscrptionId)

	if "" == resp {
		uc.Ctx.Header("status", "404")
	}
	return resp
}

func (uc *UserController) Do() {
	switch uc.protype {
	case sublist:
		uc.Ctx.JSON(json.RawMessage(uc.list()))
		break
	case nsilevel:
		uc.Ctx.JSON(json.RawMessage(uc.nsilevel()))
		break
	case subres:
		uc.Ctx.JSON(json.RawMessage(uc.subres(uc.param["subscrptionId"])))
		break
	}
	go func() {
		uc.notify <- true
	}()
	return
}

//UserController
type UserController struct {
	Ctx     iris.Context
	protype int
	param   map[string]string
	notify  chan bool
}

//User
type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

const (
	min = iota
	sublist
	nsilevel
	subres
)
